import asyncio
import qasync
import sys,os,time
from threading import Thread
# 第三方库导入
from PyQt5.QtCore import Qt, pyqtSignal, QThread  # 修改：添加QThread导入
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem,
    QHeaderView, QMessageBox, QStackedWidget, QComboBox, QFormLayout,
    QDialog, QDialogButtonBox, QStyleFactory, QGraphicsDropShadowEffect,
    QSizePolicy, QButtonGroup  # 新增 QButtonGroup
)

from PyQt5.QtGui import QFont, QIcon, QPixmap, QColor, QDoubleValidator, QIntValidator
from qasync import QEventLoop,asyncSlot

#第一种写法：
# async def sync_work(lp):
# 	asyncio.sleep(1)
# 	while True:
# 		print(f"调用协程函数 {time.strftime('%X')} {lp}")

#第二种写法：把协程放到独立线程中
# async def sync_work(lp):
# 	await asyncio.sleep(1)
# 	while True:
# 		print(f"调用协程函数 {time.strftime('%X')} {lp}")

#第三种写法，使用qasync
self.loop=''
@asyncSlot()
async def sync_work(lp):
	await asyncio.sleep(1)
	while True:
		print(f"调用协程函数 {time.strftime('%X')} {lp}")

async def run():
	 self.loop = asyncio.new_event_loop()
	 asyncio.set_event_loop(self.loop) 
	 index=[1,2,3,4,5]
	 task=asyncio.create_task(sync_work(10))
	 await task
	 #loop.run_until_complete(*task)

def start_task():
    """启动异步任务"""
    # if 	thread is None or not thread.isRunning():
        # thread = AsyncWorker()
        # thread.result_ready.connect(on_task_done)
        # thread.start()
    # Thread(target=run(),daemon=True).start()
    loop.run_until_complete(self.loop)

if __name__ == '__main__':
	# asyncio.run(sync_work())
	
	#方法一：调用协程函数和PyQt窗口，互相排斥
	# app = QApplication(sys.argv)
	# window = QWidget()
	# window.setWindowTitle('简单窗口示例')
	# window.setGeometry(100,100,400,300)
	# window.show()
	# sys.exit(app.exec_())
	# run()

	#方法二：会阻塞主窗口的显示
	# Thread(target=run(), daemon=True).start()
	# app = QApplication(sys.argv)
	# window = QWidget()
	# window.setWindowTitle('简单窗口示例')
	# window.setGeometry(100,100,400,300)
	# window.show()	
	# sys.exit(app.exec_())

	#方法三：使用qasync，还是会阻塞窗口的显示
	# app = QApplication(sys.argv)
	# window = QWidget()
	# window.setWindowTitle('简单窗口示例')
	# window.setGeometry(100,100,400,300)
	# window.show()	
	# qasync.run(sync_work(10))	
	# sys.exit(app.exec_())

	#方法四：
	# app=QApplication(sys.argv)
	# loop=QEventLoop(app)
	# window=QWidget()
	# window.setWindowTitle('简单窗口示例')
	# window.setGeometry(100,100,400,300)
	# window.show()
	# asyncio.set_event_loop(loop)
	# Thread(target=sync_work(10),daemon=True).start()
	# with loop:
	# 	loop.run_forever()

	#方法五：
	app = QApplication(sys.argv)
	window = QWidget()
	window.setWindowTitle('简单窗口示例')
	window.setGeometry(100,100,400,300)
	window.show()	
	run()	
	sys.exit(app.exec_())


